<?php

namespace app\modules\system\controllers;

use app\controllers\BaseController;
use app\services\ProductUser;
use app\services\User;
use app\utils\Utils;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;


class UserController extends BaseController
{
    public function actionList($data = 0)
    {
        if (!$data) {
            return $this->render('list');
        }

        $request = Yii::$app->request;

        $where[] = ['<>', 'id', 1];
        $where[] = ['status' => [10, 20]];

        if ($search = Utils::formUnserialize($request->post('searchData'))) {
            foreach ($search as $k => $v) {
                if ($v === '') {
                    continue;
                }
                switch ($k) {
                    case 'order_no':
                        $where[] = ['id' => Utils::getNumeric($v, 'USER')];
                        break;
                    case 'username':
                    case 'status':
                        $where[] = [$k => $v];
                        break;
                    default:
                        $where[] = ['like', $k, $v];
                        break;
                }
            }
        }

        $result = User::listPage($where, '*', 'id DESC', $request->post('page', 1), $request->post('limit', 10));
        $return = ArrayHelper::toArray($result);

        foreach ($result['data'] as $key => $val) {
            $return['data'][$key]['order_no'] = Utils::generateOrderNo('USER', $val->id);
            $return['data'][$key]['created_at'] = date('Y-m-d H:i:s', $val->created_at);
            $return['data'][$key]['status'] = $val::getStatus()[$val->status];
        }
        return $this->asJson($return);
    }

    public function actionCreate()
    {
        $request = Yii::$app->request;
        $post = $request->post();

        if ($request->isPost) {
            $model = new User();
            $post['role_id'] = isset($post['role_id']) ? implode(',', $post['role_id']) : '';
            $model->load($post, '');
            $model->setPassword($model->password);

            if (!$model->save()) return $this->error($model->errors);

            if (isset($post['product'])) {
                foreach ($post['product'] as $val) {
                    $pUser = new ProductUser();
                    $pUser->product_id = $val;
                    $pUser->user_id = $model->id;
                    $pUser->save();
                }
            }

            $model->operation_log->create($this, "创建了用户 {$model->username}", Url::to(['view', 'id' => $model->id]));
            return $this->success([], '创建成功');
        }

        return $this->render('create');
    }

    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $post = $request->post();

        if ($request->isPost) {
            $model = User::findOne(['id' => $post['id'], 'status' => [10, 20]]);
            $post['role_id'] = isset($post['role_id']) ? implode(',', $post['role_id']) : '';
            $password = $post['password'];
            unset($post['password']);
            $model->load($post, '');
            if ($password) {
                $model->setPassword($password);
            }

            if (!$model->save()) return $this->error($model->errors);

            ProductUser::updateAll(['status' => 0], ['user_id' => $model->id]);
            if (isset($post['product'])) {
                foreach ($post['product'] as $val) {
                    $pUser = ProductUser::findOne(['product_id' => $val, 'user_id' => $model->id]) ?: new ProductUser();
                    $pUser->product_id = $val;
                    $pUser->user_id = $model->id;
                    $pUser->status = 10;
                    $pUser->save();
                }
            }

            $model->operation_log->create($this, "编辑了用户 {$model->username}", Url::to(['view', 'id' => $model->id]));
            return $this->success([], '创建成功');
        }

        if (!$model = User::findOne(['id' => $id, 'status' => [10, 20]])) {
            return $this->alert('未找到该用户');
        }

        return $this->render('update', ['model' => $model, 'product_array' => $model->getSelfProductIdArray()]);
    }

    public function actionView($id)
    {
        if (!$model = User::findOne(['id' => $id, 'status' => [10, 20]])) {
            return $this->alert('未找到该用户');
        }

        return $this->render('view', ['model' => $model, 'product_array' => $model->getSelfProductIdArray()]);
    }

    public function actionDelete($id)
    {
        if (!$model = User::findOne(['id' => $id, 'status' => [10, 20]])) {
            return $this->error('未找到该用户');
        }
        $model->status = 0;
        $model->save();

        $model->operation_log->create($this, "删除了用户 {$model->username}");
        return $this->success([], '删除成功');
    }
}
